package cn.cai.controller;

import cn.cai.pojo.BasicInformation;
import cn.cai.pojo.Parameter;
import cn.cai.pojo.QueryData;
import cn.cai.pojo.ResponseData;
import cn.cai.service.BasicInformationService;
import cn.cai.service.ReportPeace;
import com.alibaba.fastjson.JSONArray;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;

@RestController
public class APIController {
    @Autowired
    private BasicInformationService basicInformationService;
    @Autowired
    private ReportPeace reportPeace;
    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    @PostMapping("/addInformation")
    private String addInformation(BasicInformation basicInformation){
        if (ObjectUtils.isEmpty(basicInformation)){
            return "请正确输入参数";
        }
        // 添加到任务队列中
        redisTemplate.opsForList().rightPush("allTask", basicInformation);
        // 添加到数据库中
        basicInformationService.addInformation(basicInformation);
        return "上传成功,上报信息会以邮件的形式发送致您的邮箱";
    }

    @PostMapping("/addOneInformation")
    private String addOneInformation(BasicInformation basicInformation){
        if (ObjectUtils.isEmpty(basicInformation)){
            return null;
        }
        // 发起post请求报平安
        basicInformation.setSbsj(LocalDateTime.now());
        Parameter parameter = new Parameter();
        BeanUtils.copyProperties(basicInformation,parameter);
        try {
            ResponseData responseData = reportPeace.sendParamForPost(parameter);

            if (responseData != null){
                return JSONArray.toJSONString(reportPeace.queryDataForGet(parameter.getXh()));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    // 查询上报情况
    @PostMapping("/inquery")
    public String inquery(String xh){
        if (ObjectUtils.isEmpty(xh)){
            return "学号不能为空";
        }
        // 判断学号的位数是否符合要求 1911014001
        if (xh.length() != 10){
            return "输入的学号不正确";
        }
        //查询情况
        List<QueryData> list = reportPeace.queryDataForGet(xh);
        return JSONArray.toJSONString(list);
    }


}
